package com.motong.gongdan.controller.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.motong.gongdan.config.ResponseData;
import com.motong.gongdan.config.auth.UserLoginToken;
import com.motong.gongdan.service.MissionService;
import com.motong.gongdan.service.ProcessesService;
import com.motong.gongdan.service.WorkOrderService;
import com.motong.gongdan.service.WorkReportService;
import com.motong.gongdan.util.LoginUtil;
import com.motong.gongdan.util.RedisUtil;
import com.motong.gongdan.util.StringUtil;
import com.motong.gongdan.util.TimeUtil;
import com.motong.gongdan.vo.system.otherVo.HomeProcessListVo;
import com.motong.gongdan.vo.system.otherVo.ProcessSetVo;
import com.motong.gongdan.vo.system.otherVo.TypeVo;
import com.motong.gongdan.vo.resp.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:fff
 * @time:2022/3/16
 */
@Api(value = "主页", tags = {"主页"})
@RestController
@RequestMapping(value = "/sys/home/")
public class HomeController {
    @Resource
    ProcessesService processesService;
    @Resource
    WorkReportService workReportService;
    @Resource
    MissionService missionService;
    @Resource
    WorkOrderService workOrderService;


    @ApiOperation(value = "首页")
    @UserLoginToken
    @RequestMapping(value = "process_list", method = RequestMethod.POST)
    public ResponseData processList(@RequestBody HomeProcessListVo vo) {
        List<String> list = new ArrayList<>();
        if (vo.getContainNotStart() == 1) {
            list.add("0");
            list.add("1");
            list.add("2");
        } else {
            list.add("1");
            list.add("2");
        }
        String time = TimeUtil.getDateDefaultStringTwo(new Date());
        if ("yesterday".equals(vo.getType())) {
            time = TimeUtil.beforeOneDay();
        } else if ("month".equals(vo.getType())) {
            time = null;
        }
        List<ProcessSetVo.vo> setVo = new ArrayList<>();
        JSONObject jsonObject = (JSONObject) RedisUtil.get("home:pmSet:" + LoginUtil.getLoginUserId());
        if (vo.getIsDetail() == 0) {
            List<ProcessListHomeResp> dataList = processesService.getBaseMapper().getListForHomeProcessList(time, vo.getContainNotStart());
            if (!CollectionUtils.isEmpty(dataList)) {
                dataList.forEach(d -> {
                    boolean b = d.getPlanedNumber().compareTo(BigDecimal.ZERO) == 0;
                    boolean b1 = d.getGoodProductNumber().compareTo(BigDecimal.ZERO) == 0;
                    if (!b && !b1) {
                        d.setRate((d.getGoodProductNumber().divide(d.getPlanedNumber(),
                                4, RoundingMode.DOWN)).multiply(BigDecimal.valueOf(100)));
                    } else {
                        d.setRate(BigDecimal.ZERO);
                    }
                    if (jsonObject == null || jsonObject.isEmpty()) {
                        ProcessSetVo.vo voSet = new ProcessSetVo.vo();
                        voSet.setName(d.getProcessName());
                        voSet.setFlag(true);
                        setVo.add(voSet);
                    }
                });
            }
            if (!CollectionUtils.isEmpty(setVo)) {
                ProcessSetVo processSetVo = new ProcessSetVo();
                processSetVo.setVos(setVo);
                RedisUtil.set("home:pmSet:" + LoginUtil.getLoginUserId(), JSONObject.parseObject(JSON.toJSONString(processSetVo)));
            }
            return ResponseData.success(dataList);
        } else {
            IPage<ProduceTaskMessResp> data = missionService.getBaseMapper().getProduceTaskMess(new Page(vo.getPage(), vo.getLimit()),
                    new QueryWrapper<ProduceTaskMessResp>().eq("p2.id", vo.getId())/*.eq(vo.getContainNotStart()==0,"m.process_state",1)*/
                            .in(/*vo.getContainNotStart()==1,*/"m.process_state", list), time, vo.getContainNotStart());
            // 获取工序的顺序
            if (Objects.nonNull(data.getRecords()) && !data.getRecords().isEmpty()) {
                Set<String> workOrderCodes = data.getRecords().stream().filter(i -> i.getProcessOrder() == 0).map(ProduceTaskMessResp::getWorkOrderCode).collect(Collectors.toSet());
                if (!workOrderCodes.isEmpty()) {
                    List<Map<String, Object>> countDataMap = missionService.getCountGroupByWorkOrder(workOrderCodes);
                    Map<String, Integer> codeCountMap = new HashMap<>(countDataMap.size());
                    countDataMap.forEach(i -> codeCountMap.put(i.get("code").toString(), Integer.valueOf(i.get("count").toString())));
                    data.getRecords().forEach(i -> i.setProcessOrder(codeCountMap.getOrDefault(i.getWorkOrderCode(), i.getProcessOrder())));
                }
            }

            return ResponseData.success(data);
        }
    }

    @UserLoginToken
    @ApiOperation(value = "工单进度报表")
    @RequestMapping(value = "schedule", method = RequestMethod.POST)
    public ResponseData schedule(@RequestBody TypeVo vo) {
        IPage<HomeScheduleResp> data = workOrderService.getBaseMapper().getHomeScheduleData(new Page(vo.getPage(), vo.getLimit()), vo.getType());
        if (!CollectionUtils.isEmpty(data.getRecords())) {
            data.getRecords().forEach(d -> {
                if (StringUtil.isNotBlank(d.getProcessIds())) {
                    List<String> ids = Arrays.asList(d.getProcessIds().split(","));
                    List<WOProcessListResp> list = processesService.getBaseMapper().getWorkOrderProcessByIds(ids, d.getWorkOrderCode());
                    d.setList(list);
                }
                if (d.getWoState() != 2 && d.getWoState() != 3) {
                    if (TimeUtil.afterNow(d.getEndTime())) {
                        d.setIsDelay(0);
                    } else {
                        d.setIsDelay(1);
                    }
                } else {
                    d.setIsDelay(0);
                }
            });
        }
        return ResponseData.success(data);
    }

    @UserLoginToken
    @ApiOperation(value = "绩效指标")
    @RequestMapping(value = "production", method = RequestMethod.POST)
    public ResponseData production(@RequestBody HomeProcessListVo vo) {
        JSONObject jsonObject = null;
        if (vo.getType().equals("yesterday")) {
            jsonObject = (JSONObject) RedisUtil.get("production:yesterday:" + LoginUtil.getLoginUserFactory());
        } else if (vo.getType().equals("month")) {
            jsonObject = (JSONObject) RedisUtil.get("production:month:" + LoginUtil.getLoginUserFactory());
        } else {
            jsonObject = (JSONObject) RedisUtil.get("production:day:" + LoginUtil.getLoginUserFactory());
        }

        if (jsonObject == null) {
            ProductionResp pr = new ProductionResp();
            pr.setAverageProduce(BigDecimal.ZERO);
            pr.setAllCompletedNumber(BigDecimal.ZERO);
            pr.setBadProductRate(BigDecimal.ZERO);
            pr.setAllPlanedNumber(BigDecimal.ZERO);
            pr.setWorkOrderNumber(BigDecimal.ZERO);
            pr.setNotFinished(BigDecimal.ZERO);
            jsonObject = (JSONObject) JSONObject.toJSON(pr);
        }
        return ResponseData.success(jsonObject.toJavaObject(ProductionResp.class));
    }

    @UserLoginToken
    @ApiOperation(value = "生产实时播报")
    @RequestMapping(value = "produce_report", method = RequestMethod.POST)
    public ResponseData produceReport() {
        List<HomeProduceReportResp> list = workReportService.getBaseMapper().getHomeProduceReport();
        return ResponseData.success(list);
    }

    @UserLoginToken
    @ApiOperation(value = "主页工序任务设置")
    @RequestMapping(value = "pm_set", method = RequestMethod.POST)
    public ResponseData pmSet(@RequestBody ProcessSetVo vo) {
        if (vo != null && !CollectionUtils.isEmpty(vo.getVos())) {
            RedisUtil.set("home:pmSet:" + LoginUtil.getLoginUserId(), JSONObject.parseObject(JSON.toJSONString(vo)));
        } else {
            JSONObject jsonObject = (JSONObject) RedisUtil.get("home:pmSet:" + LoginUtil.getLoginUserId());
            if (Objects.isNull(jsonObject)) {
                return ResponseData.success(null);
            }
            return ResponseData.success(jsonObject.toJavaObject(ProcessSetVo.class));
        }
        return ResponseData.success("success");
    }

}
